// pages/room/room.js
var util = require('../../utils/util.js')
var weChatLogin = require('../wechatLogin/wechatLogin.js')
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    requestInfo: {
      'token_id': ''
    },
    defaultInfo: {
      'create_judge': '成为法官',
      'leave_room': '离开房间',
      'revoke': '撤销操作',
      'leave_seat': '离开座位',
      'role_2': '../../images/role_2.png',
      'role_3': '../../images/role_3.png',
      'role_4': '../../images/role_4.png',
      'out': '../../images/out.png',
      'win': '../../images/win.png',
      'fail': '../../images/fail.png',
      'end': '结束本局',
      'restart': '再玩一局',
      'more_score': '积分详情'
    },
    roomInfo: {},
    userList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    console.log('111', options)
    var activity_id = options.activity_id
    // var activity_id = '2017-10-25153131728364feb5b96de2e77e1abcf73c4996'
    var requestInfo = that.data.requestInfo
    requestInfo.activity_id = activity_id
    that.setData({
      requestInfo: requestInfo
    })
    var initFunction = function () {
      that.createParticipate()
      that.getRoomDetail()
    }
    weChatLogin.logIn(that, initFunction)
  },

  //前往报名
  createParticipate: function () {
    var that = this
    var requestInfo = that.data.requestInfo
    app.createParticipate(function (callBackInfo) {
      console.log('--', callBackInfo)
      // if (callBackInfo.status == 'SUCCESS') {
      //   var callBackData = callBackInfo.data
      //   that.setData({
      //     roomInfo: callBackData
      //   })
        
      // }
    },
      requestInfo)
  },

  //获取活动详情
  getRoomDetail: function () {
    var that = this
    var requestInfo = that.data.requestInfo
    var userList = that.data.userList
    if(userList.length == 0){
      for (var i = 0; i < 12; i++) {
        userList.push({
          'user_index': i + 1, 'user_imgpath': '../../images/empty_location.png',
          'user_name': '空座',
          'user_id': '',
          'roletype_id': '0',
          'out_state': false,
          'score': 0, 
        })
      }
    }
    else{
      for (var i = 0; i < 12; i++) {
        userList[i] = {
          'user_index': i + 1, 'user_imgpath': '../../images/empty_location.png',
          'user_name': '空座',
          'user_id': '',
          'roletype_id': '0',
          'out_state': false,
          'score': 0,
        }
      }
    }
    app.getRoomDetail(function (callBackInfo) {
      if (callBackInfo.status == 'SUCCESS') {
        var callBackData = callBackInfo.data
        for(var i=0; i<callBackData.role_list.length; i++){
          var role = callBackData.role_list[i]
          var role_index = role.location - 1
          if(role_index >= 0){
            userList[role_index].user_imgpath = role.imgpath
            userList[role_index].user_name = role.user_name
            userList[role_index].user_id = role.user_id
            userList[role_index].roletype_id = role.roletype_id
            userList[role_index].out_state = role.state
            userList[role_index].score = role.score
          }
        }
        that.setData({
          roomInfo: callBackData,
          userList: userList
        })
        console.log('--', that.data.roomInfo)
        console.log('--', that.data.userList)
      }
    },
      requestInfo)
    wx.stopPullDownRefresh()
  },

  //结束本局
  endActivity: function(){
    var that = this
    var requestInfo = that.data.requestInfo
    wx.showModal({
      title: '提示',
      content: '结束后将无法恢复，是否确定结束本局！',
      confirmColor: '#5F56C1',
      success: function (res) {
        var _state = res.confirm
        if (_state == true) {
          app.endActivity(function (callBackInfo) {
            console.log('结束本局', callBackInfo)
            if (callBackInfo.status == 'SUCCESS') {
              that.getRoomDetail()
            }
          }, requestInfo)
        }
      }
    })
  },

  //成为法官
  createJudge: function(){
    var that = this
    var requestInfo = that.data.requestInfo
    var roomInfo = that.data.roomInfo
    var userList = that.data.userList
    app.createJudge(function(callBackInfo){
      if (callBackInfo.status == 'SUCCESS') {

        that.getRoomDetail()
      }
    }, requestInfo)
    console.log('11111', userList)
  },

  //撤销
  revokeOperate: function(){
    var that = this
    var requestInfo = that.data.requestInfo
    app.revokeOperate(function (callBackInfo) {
      console.log('撤销', callBackInfo)
      if (callBackInfo.status == 'SUCCESS') {
        that.getRoomDetail()
      }
      else{
        wx.showModal({
          title: '提示',
          content: '已经是最后一步，无法撤销！',
          confirmColor: '#5F56C1',
          success: function (res) { }
        })
      }
    }, requestInfo)
  },

  //法官离座
  judgeLeaveSeat: function () {
    var that = this
    var requestInfo = that.data.requestInfo
    wx.showModal({
      title: '提示',
      content: '是否确定要离开法官座位！',
      confirmColor: '#5F56C1',
      success: function (res) { 
        var _state = res.confirm
        if (_state == true){
          app.judgeLeaveSeat(function (callBackInfo) {
            console.log('法官离座', callBackInfo)
            if (callBackInfo.status == 'SUCCESS') {
              that.getRoomDetail()
            }
          }, requestInfo)
        }
      }
    })

  },

  //点击头像
  clickUser: function(res){
    var that = this
    var roomInfo = that.data.roomInfo
    //判断是否是本场法官，分配角色 or 踢出用户
    var _activity_state = roomInfo.activity_detail.activity_state
    var _roletype_id = roomInfo.my_info.roletype_id
    var user_id = res.currentTarget.dataset.userid
    var type_id = res.currentTarget.dataset.typeid
    var user_index = res.currentTarget.dataset.userindex
    var out_state = res.currentTarget.dataset.outstate
    if(_roletype_id == '1'){
      console.log('0990', out_state, user_id, type_id)
      if(_activity_state == 1 && user_id != '' && type_id == '0'){
        that.assignRole(user_id)
      }
      else if (out_state == false && user_id != '' && type_id != '0'){
        that.participantOut(user_id)
      }
    }
    else if (_roletype_id == '0'){
      if (_activity_state == 1 && user_id == '' && type_id == '0') {
        that.assignLocation(user_index)
      }
    }
  },

  //分配角色
  assignRole: function (user_id){
    var that = this
    wx.showActionSheet({
      itemList: ['村民', '神民', '狼人'],
      success: function (res) {
        var _index = res.tapIndex + 2
        var requestInfo = {}
        requestInfo['token_id'] = that.data.requestInfo.token_id
        requestInfo['foreign_id_list'] = [user_id]
        requestInfo['roletype_id'] = _index
        requestInfo['activity_id'] = that.data.requestInfo.activity_id
        app.assignRole(function(callBackInfo){
          console.log('分配角色', callBackInfo)
          if (callBackInfo.status == 'SUCCESS') {
            that.getRoomDetail()
          }
        }, requestInfo)
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },


  //变更位置
  assignLocation: function (user_index) {
    var that = this
    var roomInfo = that.data.roomInfo
    var role_index = roomInfo.my_info.location - 1
    var userList = that.data.userList
    var requestInfo = {}
    requestInfo['token_id'] = that.data.requestInfo.token_id
    requestInfo['location'] = user_index
    requestInfo['activity_id'] = that.data.requestInfo.activity_id
    app.assignLocation(function (callBackInfo) {
      console.log('变更位置', callBackInfo)
      if (callBackInfo.status == 'SUCCESS') {
        if(role_index >= 0){
          userList[role_index].user_imgpath = '../../images/empty_location.png'
          userList[role_index].user_name = '空座'
          userList[role_index].user_id = ''
          userList[role_index].roletype_id = '0'
          that.setData({
            userList: userList
          })
        }
        that.getRoomDetail()
      }
    }, requestInfo)
  },

  //出局
  participantOut: function (user_id){
    var that = this
    //判断所有成员已经分配角色
    var role_list = that.data.roomInfo.role_list
    var role_all_assign = true
    var role_score = false
    for(var i=0; i< role_list.length; i++){
      if(role_list[i].roletype_id == '0'){
        role_all_assign = false
      }
      if(role_list[i].score != '0'){
        role_score = true
      }
    }
    if (role_all_assign == true && role_score == false){
      var requestInfo = {}
      requestInfo['token_id'] = that.data.requestInfo.token_id
      requestInfo['foreign_id'] = user_id
      requestInfo['activity_id'] = that.data.requestInfo.activity_id
      wx.showModal({
        title: '提示',
        content: '是否确定出局？',
        confirmColor: '#5F56C1',
        success: function (res) {
          var _state = res.confirm
          if (_state == true) {
            app.participantOut(function (callBackInfo) {
              console.log('出局', callBackInfo)
              if (callBackInfo.status == 'SUCCESS') {
                that.getRoomDetail()
              }
            }, requestInfo)
          }
        }
      })
    }
    
  },

  //再玩一局
  reCreateActivity: function(){
    var that = this
    var requestInfo = {}
    requestInfo['token_id'] = that.data.requestInfo.token_id
    requestInfo['activity_id'] = that.data.requestInfo.activity_id
    wx.showModal({
      title: '提示',
      content: '是否确定再玩一局？',
      confirmColor: '#5F56C1',
      success: function (res) {
        var _state = res.confirm
        if (_state == true) {
          wx.showLoading({
            title: '创建中',
            mask: true
          })
          app.reCreateActivity(function (callBackInfo) {
            console.log('再玩一局', callBackInfo)
            if (callBackInfo.status == 'SUCCESS') {
              wx.hideLoading()
              wx.redirectTo({
                url: '../room/room?activity_id=' + callBackInfo['data'],
              })
            }
          }, requestInfo)
        }
      }
    })
  },

  //离开房间
  userLeaveRoom: function(){
    var that = this
    var userList = that.data.userList
    var roomInfo = that.data.roomInfo
    var requestInfo = {}
    requestInfo['token_id'] = that.data.requestInfo.token_id
    requestInfo['activity_id'] = that.data.requestInfo.activity_id
    wx.showModal({
      title: '提示',
      content: '是否确定离开房间？',
      confirmColor: '#5F56C1',
      success: function (res) {
        var _state = res.confirm
        if (_state == true) {

          app.userLeaveRoom(function (callBackInfo) {
            console.log('离开房间', callBackInfo)
            if (callBackInfo.status == 'SUCCESS') {
              wx.switchTab({
                url: '../homePage/homePage'
              })
            }
          }, requestInfo)
        }
      }
    })
  },

  //离开房间
  goToRoomScore: function () {
    var that = this
    var activity_id = that.data.requestInfo.activity_id
    wx.navigateTo({
      url: '../roomScore/roomScore?activity_id=' + activity_id,
    })
    
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function (res) {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (res) {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this
    that.getRoomDetail()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '狼人杀',
      path: '/pages/homePage/homePage',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  }
})